# -*- encoding: utf-8 -*-
"""
@File  :   mockapi.py  
@lastModifyTime  :   2021-11-19
接口调试
"""

import threading
from time import sleep
import sys
import json
from flask import Flask, request, jsonify
from flask.globals import g
from flask.signals import _signals
import hashlib
import os
from flask import make_response
from flask_cors import CORS
import sqlite3



LOCK = threading.Lock()
# 重写row_factory方法，实现拉取字典结构数据
def dict_factory(cursor, row):    
  d = {}  
  for idx, col in enumerate(cursor.description):  
    d[col[0]] = row[idx]  
  return d  

class dbconn():
  def __init__(self,dbname):   
    isNewDb = False if os.path.exists(dbname) else True
    connParms = self.ConnectDb(dbname)

    if connParms:
      self.conn,self.cur = connParms
      self.isConnect = True
      if isNewDb:self.InitDb() # 新数据库初始化数据
    else:
      self.isConnect = False
   
  def __del__(self):
    self.conn.close()

  def ConnectDb(self,db):    
    try:
      conn = sqlite3.connect(db, timeout=3, isolation_level=None,check_same_thread=False) 
      conn.row_factory = dict_factory
      cur = conn.cursor()     
      return conn,cur
    except BaseException as e:
      print("connectDb err:", e)
      return False

  # 新增记录单条记录
  def InsertRow(self, table, items):      
    # table:表格名称
    # items:字典数据
    try:
      LOCK.acquire(True)
      fields = ','.join([x for x in items])
      values = ','.join([f"'{items[key]}'" for key in items])
      sql = f"INSERT INTO {table} ({fields}) VALUES ({values})"
      self.cur.execute(sql)    
      self.conn.commit()
      return {'code':"0","data":"insert success!"}
    except Exception as e:
      return {'code':"-1","data":e.__str__()}
    finally:
      LOCK.release()

  # SQL语句执行
  def Exec(self,scripts):      
    # scripts：检索语句
    # print(scripts)
    try:
      LOCK.acquire(True)
      self.cur.execute(scripts)
      _data = self.cur.fetchall()   

      return {'code':"0","data":_data}
    except Exception as e:
      return {'code':"-1","data":e.__str__()}
    finally:
      LOCK.release()
    # return {'code':"-1","data":scripts}    

  def InitDb(self):
    sql = '''
    CREATE TABLE test (id TEXT PRIMARY KEY NOT NULL, item TEXT NOT NULL)
    '''
    self.cur.execute(sql)
    self.conn.commit()  


app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app, supports_credentials=True, resources=r'/*')

# @app.route('/api/user/login', methods=["POST", "GET"])
# @cross_origin()#通过装饰路线具体CORS 
# def login():
#     headers = {
#         'Content-Type': 'application/json',    
#         'Access-Control-Allow-Methods': "POST, GET, OPTIONS, DELETE"
#     }
#     return make_response((jsonify({'error_code': 0}), 202, headers))

@app.route('/db/exec', methods=['POST'])
def db_exec():
  _data = request.get_json()
  res = db.Exec(_data["sql"])
  return jsonify(res)

@app.route('/db/insertrow', methods=['POST'])
def db_insertrow():
  _data = request.get_json() 
  res = db.InsertRow(_data["table"],_data["items"])    
  return jsonify(res)


@app.route('/db/addTask', methods=['POST'])
def db_addtask():
  _data = request.get_json()    
  _values = _data["_reports"]    
  _sql = "insert into report (rid,pid,path,nostamppath,name,ordernum,ocred,matched,MultiPageOrder,archived,uploaded,granted,ignored,grantId,reportNum,accessType,ocrresult,matchedStr,matchErr,archiveErr) " + _values      
  db.Exec(_sql)  
  res = db.InsertRow("task",_data["_task"])  
  return jsonify({'code':"0","data":_data["_task"]})

@app.route('/db/taskIsExist', methods=['POST'])
def db_taskIsExist():
  _data = request.get_json() 
  orgFileLis = _data["fileList"]
  params = ",".join([f"'{x}'" for x in orgFileLis])
  sql = f"select path from task where path in ({params}) "
  _res = db.Exec(sql)
  print(_res)
  for p in _res["data"]:
    print(p)
    orgFileLis.remove(p["path"])

  return jsonify(orgFileLis) 
    
@app.route("/")
@app.route("/index")
def index():
  return "报告归档本地API 调试版本"

if __name__ == '__main__':
  db = dbconn('d:/esapidb/database.db')          
  app.run(host='0.0.0.0', port=3123, debug=True)